package org.dromara.exam.service.impl;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.RequiredArgsConstructor;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.exam.domain.dto.TemplateSchema;
import org.dromara.exam.domain.entity.ExamTemplate;
import org.dromara.exam.domain.vo.CountByMonthVo;
import org.dromara.exam.domain.vo.CountScoreVo;
import org.dromara.exam.mapper.DataDisplayMapper;
import org.dromara.exam.mapper.ExamTemplateMapper;
import org.dromara.exam.service.IDataDisplayService;
import org.dromara.system.domain.entity.SysDept;
import org.dromara.system.domain.entity.SysUser;
import org.dromara.system.domain.bo.SysDeptBo;
import org.dromara.system.mapper.SysDeptMapper;
import org.dromara.system.mapper.SysUserMapper;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author :xiyin321
 * @since : 2024/6/9 23:03
 */
@Service
@RequiredArgsConstructor
public class DataDisplayServiceImpl implements IDataDisplayService {

    private final DataDisplayMapper baseMapper;
    private final SysUserMapper sysUserMapper;
    private final ExamTemplateMapper examTemplateMapper;
    private final SysDeptMapper sysDeptMapper;

    /*获取用户数量*/
    @Override
    public Long queryUserCount() {
        return sysUserMapper.selectCount(new LambdaQueryWrapper<SysUser>()
            .eq(SysUser::getDelFlag, "0"));
    }


    /*获取题目数量*/
    @Override
    public Long queryQuestionCount() {
        return examTemplateMapper.selectCount(new LambdaQueryWrapper<ExamTemplate>()
            .eq(ExamTemplate::getDelFlag, "0"));
    }

    /*获取部门数量*/
    @Override
    public Long queryDeptCount(SysDeptBo bo) {
        return sysDeptMapper.selectCount(new LambdaQueryWrapper<SysDept>()
            .eq(SysDept::getDelFlag, "0")
            .eq(bo.getDeptType() != null, SysDept::getDeptType, bo.getDeptType()));
    }

    /*查询题目数量*/
    @Override
    public List<CountByMonthVo> queryQuestionCountByMonth() {
        return baseMapper.selectQuestionCountByMonth();
    }

    /*查询答卷数量*/
    @Override
    public List<CountByMonthVo> queryAnswerCountByMonth() {
        return baseMapper.selectAnswerCountByMonth();
    }

    /*查询用户成绩*/
    @Override
    public List<CountScoreVo> queryUserScore() {
        List<CountScoreVo> list = baseMapper.selectPaperListByUserId(LoginHelper.getUserId());
        list.forEach(item -> {
            item.setTotalScore(JSONUtil.toBean(item.getPaperContent(), TemplateSchema.class).getAttribute().getExamScore());
        });
        return list;
    }
}
